package com.un.web.sys.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.StrUtil;
import com.un.core.cache.RedisCache;
import com.un.core.common.ComConstants;
import com.un.core.common.R;
import com.un.core.utils.MD5Util;
import com.un.core.utils.SnowFlake;
import com.un.web.sys.domain.entity.SysUser;
import com.un.web.sys.domain.vo.CodeResultVo;
import com.un.web.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author xingjian
 * @Date 2023-02-23
 **/
@RestController
@RequestMapping("wx")
public class WxCallbackController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisCache redisCache;


    @RequestMapping("callback")
    public HashMap<String, Object> callback(CodeResultVo codeResultVo){
        SysUser sysUser = null;
        sysUser=sysUserService.selectWxUser(codeResultVo.getUserId());
        if (StrUtil.isEmptyIfStr(sysUser)){
            sysUser=new SysUser();
            sysUser.setIpAddr(codeResultVo.getIpAddr());
            String salt = MD5Util.getSalt();
            sysUser.setSalt(salt);
            sysUser.setRoleId(2);
            Snowflake snowflake = new Snowflake();
            sysUser.setAccount(snowflake.nextIdStr());
            sysUser.setPassword(MD5Util.getSaltMD5(ComConstants.InitPassword, salt));
            sysUser.setAvatar(codeResultVo.getAvatar());
            sysUser.setWxTempId(codeResultVo.getTempUserId());
            sysUser.setWxUserId(codeResultVo.getUserId());
            sysUser.setName(codeResultVo.getNickname());
            sysUserService.saveUser(sysUser);
        }else {
            sysUser.setWxTempId(codeResultVo.getTempUserId());
            sysUserService.updateByPrimaryKey(sysUser);
        }

        if (StrUtil.isEmptyIfStr(codeResultVo)){
            return R.error("");
        }
        redisCache.deleteObject("wx:"+codeResultVo.getTempUserId());
        HashMap<String, Object> result = new HashMap<>();
        result.put("errcode",0);
        result.put("message","成功");
        return result;
    }
}
